<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属物业" prop="propertyId">
        <el-select v-model="queryParams.propertyId" placeholder="请选择物业" size="mini">
          <el-option v-for="property in propertyListOptions"
                     :key="property.id"
                     :label="property.propertyName"
                     :value="property.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="所属小区" prop="estateId">
        <el-select v-model="queryParams.estateId" placeholder="请选择小区" style="width:140px;" size="mini" filterable clearable>
          <el-option v-for="estate in estatesOptions"
                     :key="estate.id"
                     :label="estate.estateName"
                     :value="estate.id"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['module:cleanArea:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="areaList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="所在物业" align="center" prop="propertyName" />
      <el-table-column label="所在小区" align="center" prop="estateName" />
      <el-table-column label="保洁区域名称" align="center" prop="areaTitle" />
      <el-table-column label="区域类型" align="areaType">
        <template slot-scope="scope">
          <div>
            <el-tag style="cursor: pointer" :type="'info'">保洁</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="区域标准" align="center" prop="surveyStandardId">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="surveyStandard(scope.row)">{{scope.row.surveyName }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="二维码下载" align="center" width="170">
        <template slot-scope="scope">
          <el-popover placement="right" width="400" trigger="hover">
            <el-image style="width: 380px; height: 380px" :src="scope.row.qrCode"  fit="fill" />
            <i class="el-icon-picture" slot="reference"/>
          </el-popover>
          <el-button size="mini" type="text" icon="el-icon-download"
                     @click="downloadImg(scope.row)">{{scope.row.areaTitle }}</el-button>
        </template>
      </el-table-column>
<!--      <el-table-column label="状态" align="center">-->
<!--        <template slot-scope="scope">-->
<!--          <div>-->
<!--            <el-tag v-if="scope.row.state === 0" style="cursor: pointer" :type="'info'">停用</el-tag>-->
<!--            <el-tag v-else style="cursor: pointer" :type=" '' ">正常</el-tag>-->
<!--          </div>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="状态" align="center" key="state">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.state"
                     :active-value="1"
                     :inactive-value="0"
                     @change="handleChangeSaleOut(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-picture" @click="resetQrCode(scope.row)"
                     v-hasPermi="['module:cleanArea:edit']">生成二维码</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['module:cleanArea:edit']">修改</el-button>
<!--          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"-->
<!--                     v-hasPermi="['module:cleanArea:remove']">删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList" />

    <!-- 添加或修改保洁、绿化区域：添加保洁计划选择对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属物业" prop="propertyId">
          <el-select v-model="form.propertyId" placeholder="请选择物业" size="mini"  filterable clearable @change="selectEstate">
            <el-option v-for="property in propertyListOptions"
                       :key="property.id"
                       :label="property.propertyName"
                       :value="property.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="所属小区" prop="estateId">
          <el-select v-model="form.estateId" placeholder="请选择小区" style="width:140px;" size="mini" filterable clearable>
            <el-option v-for="estate in estatesOptions"
                       :key="estate.id"
                       :label="estate.estateName"
                       :value="estate.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="区域名称" prop="areaTitle">
          <el-input v-model="form.areaTitle" placeholder="请输入保洁区域名称" size="mini"/>
        </el-form-item>

<!--        <el-form-item label="区域范围" prop="areas"  style="width:100%;margin-top: 10px">-->
<!--          <treeselect v-model="form.areas" :options="areaRangList" :normalizer="normalizer" placeholder="请选择区域范围" multiple />-->
<!--        </el-form-item>-->

<!--        <el-form-item label=" " style="margin-top: 10px">-->
<!--          <el-button icon="el-icon-circle-plus-outline" @click="addArea()" size="mini">添加区域</el-button>-->
<!--        </el-form-item>-->

        <el-form-item label="位置信息" prop="address">
          <el-input v-model="form.address" placeholder="请输入位置信息" size="mini"/>
        </el-form-item>


        <el-form-item label="标准模板" prop="surveyStandardId">
          <el-select v-model="form.surveyStandardId" placeholder="请选择标准模板" filterable clearable size="mini" style="width:100%">
            <el-option v-for="su in surveyStandardList"
                       :key="su.id"
                       :label="su.questionTitle"
                       :value="su.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="内容模板" prop="surveyTemplateId">
          <el-select v-model="form.surveyTemplateId" placeholder="请选择内容模板" filterable clearable size="mini" style="width:100%">
            <el-option v-for="su in surveyTemplateList"
                       :key="su.id"
                       :label="su.questionTitle"
                       :value="su.id"/>
          </el-select>
        </el-form-item>


        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注信息" type="textarea"  size="mini"/>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="form.state" size="mini">
            <el-radio :value="0" :label="0">未启用</el-radio>
            <el-radio :value="1" :label="1">已启用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="titleSurvey" :visible.sync="openSurvey" width="500px" append-to-body>
      <p v-html="info">{{info}}</p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelSurvey" size="mini">取 消</el-button>
      </div>
    </el-dialog>

<!--    <el-dialog :title="title" :visible.sync="openAddArea" width="800px" append-to-body>-->
<!--      <el-row>-->
<!--        <el-col :span="10">-->
<!--          <el-card shadow="hover">-->
<!--            <el-input v-model="buildName" placeholder="楼栋名称" prefix-icon="Search" clearable />-->
<!--            <el-tree class="mt-2" ref="buildTreeRef" node-key="id" :data="buildOptions"-->
<!--                     :props="{ label: 'buildName', children: 'children' }"-->
<!--                     :expand-on-click-node="false"-->
<!--                     :filter-node-method="filterNode"-->
<!--                     highlight-current-->
<!--                     :default-expanded-keys="[buildOptions[0].id]"-->
<!--                     @node-click="handleNodeClick"/>-->
<!--          </el-card>-->
<!--        </el-col>-->
<!--        <el-col :span="12" style="margin-left: 20px">-->
<!--          <el-table v-loading="loading" :data="floorList" ref="multipleTable" @selection-change="handleArea" border>-->
<!--            <el-table-column type="selection" width="55" align="center" />-->
<!--            <el-table-column label="楼层号" align="center" prop="floorNum" />-->
<!--            <el-table-column label="楼层名称" align="center" prop="floorName" />-->
<!--            <el-table-column label="状态" align="center" prop="state">-->
<!--              <template slot-scope="scope">-->
<!--                <div>-->
<!--                  <el-tag v-if="scope.row.state === 0" style="cursor: pointer" :type="'info'">停用</el-tag>-->
<!--                  <el-tag v-if="scope.row.state === 1" style="cursor: pointer" :type="''">正常</el-tag>-->
<!--                </div>-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--          </el-table>-->
<!--        </el-col>-->
<!--      </el-row>-->
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button :loading="buttonLoading" size="mini" type="primary" @click="submitAreaForm">确 定</el-button>-->
<!--        <el-button @click="cancelArea" size="mini">取 消</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
import {
  listArea,
  getArea,
  delArea,
  addArea,
  updateArea,
  exportArea,
  resetQrCode,
  updateAreaState
} from "@/api/module/event/area/cleanArea";
import {listPropertyNoPage} from "@/api/module/property/property";
import {listAllEstate} from "@/api/module/estate/estate";
import {listSurvey} from "@/api/module/survey/survey";
import {listBuild,listBuilds} from "@/api/module/estate/build";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listFloor} from "@/api/module/estate/floor";

export default {
  name: "Area",
  components: {Treeselect},
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      isExpand: false,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 保洁、绿化区域：添加保洁计划选择表格数据
      areaList: [],
      propertyListOptions:[],
      estatesOptions:[],
      surveyTemplateList: [],
      surveyStandardList: [],
      selectData:[],
      areaRangList:[],
      floorList:[],
      buildName:undefined,
      // 弹出层标题
      title: "",
      totalBuild: 0,
      titleSurvey: "",
      // 是否显示弹出层
      open: false,
      buildOptions:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaType:3,
      },
      info:undefined,
      openSurvey:false,
      queryParamsEstate: {
        propertyId: undefined,
      },
      queryParamsSurvey: {
        pageNum: 1,
        pageSize: 100,
        propertyId: undefined,
        estateId: undefined,
        surveyType:undefined,
        functionType:3,
      },
      areaInfo:{
        buildId:undefined,
        floorIds:[],
      },
      queryParamsFloor: {
        pageNum: 1,
        pageSize: 10,
        buildId:undefined,
      },
      queryParamsBuild:{
        pageNum: 1,
        pageSize: 10,
        estateId:undefined,
        parentId:undefined,
      },
      openAddArea:false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  created() {
    this.getList();
    this.getEstateList();
    this.getPropertyList();
    // this.getTreeselect();
    // this.getBuildList();

  },
  methods: {
    // addArea(){
    //   this.open=false;
    //   this.openAddArea=true;
    // },
    surveyStandard(row){
      this.openSurvey=true;
      this.info = row.surveyInfo;
      this.titleSurvey = "标准模板";
    },
    /** 查询保洁、绿化区域：添加保洁计划选择列表 */
    getList() {
      this.loading = true;
      listArea(this.queryParams).then(response => {
        this.areaList = response.rows;
        this.total = response.total;
        console.log(response);
        this.loading = false;
      });
    },
    handleChangeSaleOut(row) {
      let text = row.state === 0 ? "启用" : "停用";
      this.$confirm('确认要修改"' + text + '"的状态吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return updateAreaState(row.id, row.state,3);
      }).then(() => {
        this.msgSuccess("修改 " + text + "成功");
        this.getList();
      }).catch(function () {
        row.state = row.state === "0" ? "1" : "0";
      });
    },
    cancelArea(){
      this.openAddArea=false;
      this.open=true;
    },
    submitAreaForm(){
      this.form.areaInfo = this.areaInfo;
      // console.log(this.form)
      this.openAddArea=false;
      this.open=true;
    },
    //查询楼数据
    // getBuildList() {
    //   this.loading = true;
    //   listBuild(this.queryParamsBuild).then(response => {
    //     this.totalBuild = response.total;
    //     this.loading = false;
    //     this.buildList = this.handleTree(response, "id", "parentId");
    //   });
    // },
    //查询层数据
    getFloorList() {
      this.loading = true;
      listFloor(this.queryParamsFloor).then(response => {
        this.floorList = response;
        this.loading = false;
      });
    },
    //节点查询
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 节点单击事件 */
    handleNodeClick(data){
      console.log('handleNodeClick',data);
      this.chooseBuildId = data.id;
      this.buildLevel = data.level;
      if(this.buildLevel  == 2){
        this.areaInfo.buildId = data.id;
        this.queryParamsFloor.unitId = data.id;
        this.queryParams.pageNum = 1;
        this.getFloorList()
      }else{
        this.form.parentId = data.id;
        this.queryParams.parentId = data.id;
      }
    },
    // getTreeselect() {
    //   listBuilds().then(response => {
    //     this.buildOptions = [];
    //     const data = { id: 0, buildName: '小区', children: [] }
    //     data.children = this.handleTree(response, "id", "parentId");
    //     console.log(response)
    //     this.buildOptions.push(data);
    //   });
    // },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.buildName,
        children: node.children
      };
    },
    downloadImg(row){
      window.location.href = process.env.VUE_APP_BASE_API + "/common/download/area/" + row.id;
    },
    resetQrCode(row){
      var data = {
        id: row.id
      };
      resetQrCode(data).then(response => {
        if(response.code === 200){
          this.msgSuccess("生成成功");
          this.getList();
        }else{
          this.msgError("生成失败");
        }
      });
    },
    getSurveyTemplateList() {
      this.queryParamsSurvey.surveyType = 1;
      listSurvey(this.queryParamsSurvey).then(response => {
        this.surveyTemplateList = response.rows;
      });
    },
    getSurveyStandardList() {
      this.queryParamsSurvey.surveyType = 2;
      listSurvey(this.queryParamsSurvey).then(response => {
        this.surveyStandardList = response.rows;
      });
    },
    resetArea(){
      this.areaInfo={
        buildId: undefined,
        floorIds: [],
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.resetArea();
      this.$refs.multipleTable.clearSelection();
    },
    cancelSurvey() {
      this.openSurvey = false;
      this.info=undefined;
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        propertyId: undefined,
        estateId: undefined,
        areaTitle: undefined,
        areaRange: undefined,
        areaType: 3,
        surveyStandardId: undefined,
        address:undefined,
        killObject:undefined,
        useDrug:undefined,
        remark: undefined,
        state: undefined,
        createTime: undefined,
        createBy: undefined,
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    getPropertyList() {
      listPropertyNoPage().then(response => {
        this.propertyListOptions = response.data;
      });
    },

    selectEstate(val){
      this.queryParamsEstate.propertyId = val;
      this.getEstateList();
    },
    getEstateList() {
      listAllEstate(this.queryParamsEstate).then(response => {
        console.log('getEstateList',response.data);
        this.estatesOptions = response.data;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length!==1;
      this.multiple = !selection.length;
    },
    handleArea(selection) {
      this.areaInfo.floorIds = selection.map(item => item.id);
      // this.form.floorName = selection.map(item => item.floorName);
      this.single = selection.length!==1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.getPropertyList()
      this.getSurveyTemplateList();
      this.getSurveyStandardList();
      this.getTreeselect();
      this.title = "添加保洁、绿化区域：添加保洁计划选择";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      this.getPropertyList()
      this.getSurveyTemplateList();
      this.getSurveyStandardList();
      // this.getTreeselect();
      const id = row.id || this.ids;
      getArea(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.selectData = response.data.areaInfo.floorIds;
        this.queryParamsFloor.buildId = response.data.areaInfo.buildId;
        this.queryParams.pageNum = 1;
        // this.getFloorList()
        this.floorList.forEach((item) => { // 表格数据遍历
          this.selectData.forEach((items) => {
            if (item.id === items) { // 找到对应项
              this.$nextTick(() => {
                this.$refs.multipleTable.toggleRowSelection(item, true);
                console.log(item);
                // 通过toggleRowSelection给对应项添加选中状态
              });
            }
          });
        });

        this.title = "修改保洁、绿化区域：添加保洁计划选择";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateArea(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.$refs.multipleTable.clearSelection();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addArea(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.$refs.multipleTable.clearSelection();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除保洁、绿化区域：添加保洁计划选择编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true;
        return delArea(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有保洁、绿化区域：添加保洁计划选择数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportArea(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    }
  }
};
</script>
